<script setup>
import {ref} from "vue";
import {useUserInfoStore} from "../../store/userInfo";
import {updatePwdAPI} from "../../api/user";
import {ElMessage} from "element-plus";
import {useTokenStore} from "../../store/token";
import {useRouter} from "vue-router/dist/vue-router";

const userInfoStore = useUserInfoStore();
const tokenStore = useTokenStore();
const router = useRouter();

// 用户数据模型
const passwordData = ref({
  username: userInfoStore.userInfo.username,
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 判断表单校验
const form = ref(null);

// 校验密码函数
const checkRePassword = (rule, value, callback) => {
  if (value == null || value === '') {
    callback(new Error('再次输入的密码不能为空'))
  } else if (value !== passwordData.value.new_pwd) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

// 表单校验规则
const rules = {
  old_pwd: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur'}
  ],
  new_pwd: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur'}
  ],
  re_pwd: [
    {validator: checkRePassword, trigger: 'blur'}
  ]
}

// 重置密码
const resetPassword = () => {
  form.value.validate(async (valid) => {
    if (valid) {
      // 执行重置密码逻辑
      const result = await updatePwdAPI(passwordData.value);
      // 提示信息
      ElMessage.success(result.message ? result.message : '密码重置成功')
      // 退出登录
      // 清除userInfo
      userInfoStore.clearUserInfo()
      // 清除token
      tokenStore.removeToken()
      // 跳转到登录页面
      router.push('/login')
    }
  })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>重置密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form ref="form" :model="passwordData" :rules="rules" label-width="100px" size="large">
          <el-form-item label="登录名称">
            <el-input v-model="passwordData.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="旧密码" prop="old_pwd">
            <el-input type="password" placeholder="请输入旧密码"
                      v-model="passwordData.old_pwd"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input type="password" placeholder="请输入新密码"
                      v-model="passwordData.new_pwd"></el-input>
          </el-form-item>
          <el-form-item prop="re_pwd">
            <el-input type="password" placeholder="请再次输入新密码"
                      v-model="passwordData.re_pwd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="resetPassword">重置密码</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
